package com.lg.houtai.logic;

import java.util.Set;

import org.apache.http.client.HttpClient;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.DebugUtils;
import android.view.KeyEvent;

import com.lg.houtai.manager.ImageManager;
import com.lg.houtai.manager.TaskManager;
import com.lg.houtai.manager.WeiboManager;
import com.lg.houtai.ui.R;

public class MainService extends Service implements Runnable {

	private boolean isrun;
	public static boolean serviceState = false;

	private TaskManager taskManager;
	private WeiboManager weiboManager;
	private ActivityManager activityManager;
	private HttpClient httpClient;
	private ImageManager imageManager;

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public void onCreate() {
		super.onCreate();
		taskManager = TaskManager.getInstance();
		weiboManager = WeiboManager.getInstance();
		activityManager = ActivityManager.getInstance();
		httpClient = HttpClient.getInstance();
		imageManager = ImageManager.getInstance();
		isrun = true;
		serviceState = true;
		Thread t = new Thread(this);
		t.start();
		new Thread(new Runnable() {
			public void run() {
				while (isrun) {
					synchronized (taskManager.getImageTaskArray()) {
						if (taskManager.getImages() > 0) {
							getImage(taskManager.getFirstImageTask());
						}
					}
					try {
						Thread.sleep(1000);
					} catch (Exception e) {
					}
				}
			}

		}).start();
	}

	private void getImage(Task task) {
		Message msg = handler.obtainMessage();
		// 处理
		BitmapDrawable image = httpClient.getImage(task.getUrl());
		switch (task.getTaskType()) {
		case TaskType.TS_GETIMAGE_AVATAR:
			imageManager.addAvatar((String) task.getData(), image);
			break;
		case TaskType.TS_GETIMAGE_PICTURE:
			imageManager.addPicture((String) task.getData(), image);
			break;
		}
		msg.obj = task;
		taskManager.removeImage(task);
		handler.sendMessage(msg);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		isrun = false;
		serviceState = false;
	}

	public void run() {
		while (isrun) {
			synchronized (taskManager.getTaskArray()) {
				if (taskManager.getSize() > 0) {
					doTask(taskManager.getTask(0));
				}
			}
			try {
				Thread.sleep(1000);
			} catch (Exception e) {
			}
		}
	}

	private void doTask(Task task) {
		Message msg = handler.obtainMessage();
		// 处理
		msg.obj = weiboManager.request(task);
		taskManager.removeTask(task);
		handler.sendMessage(msg);
	}

	public Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			Task task = (Task) msg.obj;
			try {
				activityManager.getActivity(task.getActID()).refresh(task);
			} catch (NullPointerException e) {
				DebugUtils.exception(e);
			}
		}
	};

	// 网络连接设置提示
	public static void alertNetError(final Context context) {
		AlertDialog.Builder ab = new AlertDialog.Builder(context);
		ab.setIcon(R.drawable.error);
		ab.setTitle("网络连接设置");
		ab.setMessage("现在没有可用网络，请设置网络或退出程序");
		ab.setPositiveButton("设置网络", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
				// 启动网络设置窗口
				Intent it = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
				context.startActivity(it);
			}
		});
		ab.setNegativeButton("退出程序", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// 退出程序
				// 停止服务
				Intent it = new Intent(context, MainService.class);
				context.stopService(it);

				ActivityManager manager = ActivityManager.getInstance();
				// 关掉Activity
				Set<Integer> keySet = manager.getActivityKeySet();
				for (Integer key : keySet) {
					manager.getActivity(key).finish();
				}
				android.os.Process.killProcess(android.os.Process.myPid());
			}
		});
		ab.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_BACK) {
					return true;
				}
				return false;
			}
		});
		ab.create().show();
	}
}
